package cn.lhf.cd.service;

import cn.lhf.cd.Main;
import cn.lhf.cd.domain.RecordType;
import cn.lhf.cd.entity.Record;
import cn.lhf.cd.mapper.RecordMapper;
import cn.lhf.cd.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;

public class UserService {

    /**
     * 扣除余额
     * @param userid  用户id
     * @param decimal 扣除的金额
     * @throws Exception 神奇的异常
     */
    public static void withdraw(Integer userid, BigDecimal decimal) throws Exception {
        SqlSession sqlSession = Main.openSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        if (userMapper.getMoney(userid).compareTo(decimal) < 0) {   //余额不足
            sqlSession.close();
            throw new Exception("余额不足!");
        }
        sqlSession.getMapper(RecordMapper.class).add(
                new Record(userid, decimal, RecordType.WITHDRAWAL, null)); //保存流水记录
        userMapper.withdrawMoney(userid, decimal);                                           //扣除金额
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 增加余额
     * @param userid  用户id
     * @param decimal 增加的金额
     */
    public static void plusMoney(Integer userid, BigDecimal decimal) {
        SqlSession sqlSession = Main.openSqlSession();
        sqlSession.getMapper(UserMapper.class).plusMoney(userid, decimal);                                          //增加金额
        sqlSession.getMapper(RecordMapper.class).add(
                new Record(userid, decimal, RecordType.PLUS, null));   //保存流水记录
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 转移余额
     * @param srcUserId 转出帐号
     * @param dstUserId 转入帐号
     * @param decimal   金额
     * @throws Exception 神奇的异常
     */
    public static void transfer(Integer srcUserId, Integer dstUserId, BigDecimal decimal) throws Exception {
        SqlSession sqlSession = Main.openSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        if (!userMapper.existsById(dstUserId)) {    //查找对方帐号
            sqlSession.close();
            throw new Exception("转入帐户不存在！");
        }

        if (userMapper.getMoney(srcUserId).compareTo(decimal) < 0) {
            sqlSession.close();
            throw new Exception("余额不足!");
        }
        userMapper.plusMoney(dstUserId, decimal);                   //给对方增加余额
        sqlSession.getMapper(RecordMapper.class).add(
                new Record(srcUserId, decimal, RecordType.TRANSFER, dstUserId));    //保存流水
        sqlSession.commit();
        sqlSession.close();
    }
}
